package com.lzx.action;

import java.io.File;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.lzx.utils.RandomFileRenamePolicy;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class CosUploadAction extends DispatchAction {

	public ActionForward cosUpload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println(request);
		System.out.println(request.getParameter("file1"));
		System.out.println(request.getParameter("text"));
		System.out.println("---------------------------------");
		
		
		System.out.println("---------------------------");
		// 获得根目录的物理路径
		String path = this.servlet.getServletContext().getRealPath("/");
		String saveDirectory = path + "uploadfile\\";

		File file = new File(saveDirectory);
		if (!file.exists()) {
			file.mkdirs();
		}

		// 每个文件最大5m,最多3个文件,所以...
		int maxPostSize = 3 * 5 * 1024 * 1024;
		// response的编码为"gb2312",同时采用缺省的文件名冲突解决策略,实现上传
		MultipartRequest multi = new MultipartRequest(request, saveDirectory,
				maxPostSize, "UTF-8", new RandomFileRenamePolicy());
		
		
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		

		// 用于接收文本字段
		String text = multi.getParameter("text");
		
		// 把获得的文件名放在容器中
		Enumeration files = multi.getFileNames();
		while (files.hasMoreElements()) {
			String name = (String) files.nextElement();
			File f = multi.getFile(name);
			if (f != null) {
				String fileName = multi.getFilesystemName(name);
				
				
				String oriName = multi.getOriginalFileName(name);
//				
				System.out.println(f.toString());
				f.deleteOnExit();
//				System.out.println(f.toString());
//			
//				System.out.println(fileName);
//				System.out.println(oriName);
//				
				// 在这里进行相应的操作，如存入数据库等
				out.println("上传的文件:" + fileName);
				
				out.println("<br>");
				
			}
		}
		out.print(text);
		
		out.close();
		return null;
	}

}
